﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Kokomo.Environment.Commanding;
using System.Collections.Specialized;
using System.Windows.Input;
using Kokomo.Environment.Services;

namespace Kokomo.Environment.Hosting
{
	class NewDocumentMenuViewModel : MenuItemViewModel
	{
		public ICommand CreateDocumentCommand { get; private set; }

		public NewDocumentMenuViewModel(
			ICommand createDocumentCommand,
			IEnumerable<DocumentTemplate> templates
			)
		{
			if (createDocumentCommand == null) throw new ArgumentNullException("createDocumentCommand");
			if (templates == null) throw new ArgumentNullException("templates");

			this.CreateDocumentCommand = createDocumentCommand;
			this.Templates = templates;
			INotifyCollectionChanged notifyCollection = templates as INotifyCollectionChanged;
			if (notifyCollection != null)
			{
				notifyCollection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Entries_CollectionChanged);
			}
			this.RefreshEntries();
		}

		public override UiString Text
		{
			get { return UiString.FromString(Messages.NewMenuTitle); }
		}

		public override System.Windows.Media.ImageSource IconSource
		{
			get
			{
				return EnvironmentServices.DemandService<IImageProvider>().GetImage(StandardImageKeys.NewDocument);
			}
		}

		void Entries_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			RefreshEntries();
		}

		private void RefreshEntries()
		{
			this._items = this.Templates.Select(this.CreateMenuItemForTemplate);
			this.OnPropertyChanged("Items");

			this.IsVisible = this._items.Count() > 0;
		}
		private NewDocumentMenuItemViewModel CreateMenuItemForTemplate(DocumentTemplate template)
		{
			return new NewDocumentMenuItemViewModel(template, this.CreateDocumentCommand);
		}

		public IEnumerable<DocumentTemplate> Templates { get; private set; }

		private IEnumerable<MenuItemViewModel> _items;
		public override IEnumerable<MenuItemViewModel> Items
		{
			get { return this._items; }
		}
	}
}